package com.foolishbird.sdk.assist;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;


import com.foolishbird.sdk.api.FBSDK;
import com.foolishbird.sdk.utils.WL;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class AbsWXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = AbsWXEntryActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);

        WeChatAppletOperation operation = WeChatAppletOperation.getInstance();
        if (!operation.isRegisterApp()) {
            operation.registerApp(this, FBSDK.getInstance().getWeChatAppId());
        }

        Intent intent = getIntent();
        if (intent != null) {
            String payInfo = intent.getStringExtra("wechat_applet_pay_info");
            if (!TextUtils.isEmpty(payInfo)) {
                if (!operation.startWeChatApplet(payInfo)) {
                    WL.d(TAG, "onCreate -----> start wechat applet fail.");
                    setResult(RESULT_CANCELED);
                    onFinishWXEntryActivity();
                }
            } else {
                if (!operation.handleIntent(getIntent(), this)) {
                    setResult(RESULT_CANCELED);
                    onFinishWXEntryActivity();
                }
            }
        } else {
            WL.d(TAG, "onCreate ====> intent is null");
            setResult(RESULT_CANCELED);
            onFinishWXEntryActivity();
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        setResult(RESULT_CANCELED);
        onFinishWXEntryActivity();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        WeChatAppletOperation.getInstance().handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {

    }

    /**
     * 1、原始微信小程序支付返回值：true,表示支付成功; false,表示支付失败
     * 2、乐云付微信小程序支付返回值：{errCode: '200', errMsg: '支付成功'}
     */
    @SuppressLint("LongLogTag")
    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp;
            String extraData = launchMiniProResp.extMsg;
            WL.d(TAG, "onResp ====> extraData: " + extraData);
            try {
                JSONObject jsonObject = new JSONObject(extraData);
                if (jsonObject.has("errCode")) {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    if ("200".equals(jsonObject.getString("errCode"))) {
                        observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, jsonObject.getString("errMsg"), null);
                    } else {
                        observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_FAILED, jsonObject.getString("errMsg"), null);
                    }
                } else {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, "wechat applet pay state is cancel", null);
                }
            } catch (JSONException e) {
                WL.d(TAG, "onResp ====> JSONException: " + e.getLocalizedMessage());

                if ("true".equalsIgnoreCase(extraData)) {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, "wechat applet pay state is success", null);
                } else {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, "wechat applet pay state is cancel", null);
                }
            }
        }

        setResult(RESULT_OK);
        onFinishWXEntryActivity();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WeChatAppletOperation.getInstance().unregisterApp();
    }

    protected abstract void onFinishWXEntryActivity();
}